import { debounce } from 'lodash-es'

export const DEBOUNCE_TIME = 1000

/**
 * 获取table数据
 * @param getApi  api
 * @param filterInfo 过滤器
 * @param param2 配置
 * @returns
 */
function useGetData<IListItem = any, IFilter = any>(
  getApi: (e?: any) => IResList<any>,
  filterInfo: IFilter,
  {
    // 不走防抖的过滤
    // noDebounce = [],
    // 是否先请求一次数据
    useImmediate = true,
    // 是否分页
    usePagination = true,
    // 是否防抖
    useDebounce = true,
    // req转换方法
    reqParamsFormat = (e: any) => e,
    // res转换方法
    resListFormat = (e: any) => e,
  } = {},
) {
  const data = reactive<{
    current: number
    filterInfo: IFilter
    others: any
    dataList: Array<IListItem> // 这里有点小问题...
    inDebounce: boolean
    inLoading: boolean
    total: number
  }>({
    current: 1,
    inDebounce: false,
    others: {},
    inLoading: false,
    filterInfo: {} as any,
    dataList: [],
    total: 0,
  })

  const { pageSize } = storeToRefs(useGlobal())
  onBeforeMount(async () => {
    Object.assign(data, { filterInfo })
    useImmediate && getData()
    watch(
      () => data.filterInfo,
      () => {
        if (useDebounce) {
          data.inDebounce = false
          setTimeout(() => {
            data.inDebounce = true
          })
          debounce_get()
        } else {
          getData()
        }
      },
      { deep: true },
    )
    watch(
      [() => data.current, () => pageSize.value],
      () => {
        getData()
      },
      { deep: true },
    )
  })

  //#region 获取列表数据
  const debounce_get = debounce(() => {
    data.current = 1
    getData()
  }, DEBOUNCE_TIME)

  async function getData() {
    debounce_get.cancel()
    Object.assign(data, { inDebounce: false, inLoading: true })
    const { filterInfo, current } = data
    const params = reqParamsFormat({
      ...(filterInfo as any),
      ...(usePagination ? { page: current, size: pageSize.value } : {}),
    })
    const { list, total, ...others } = await getApi(params)
    const dataList = resListFormat(list)
    Object.assign(data, { dataList, total, others })
    await nextTick()
    data.inLoading = false
  }
  //#endregion

  // 分页
  const pagination = computed(() => {
    if (!usePagination) return false
    const { total, current } = data
    // if (total < pageSize.value) return false
    return {
      current: current,
      pageSize: pageSize.value,
      total: total,
      showTotal: true,
      showJumper: true,
      showPageSize: true,
      'page-size-options': [20, 30, 50],
    }
  })

  const handlePageChange = {
    pageChange: (i: number) => (data.current = i),
    pageSizeChange: (i: number) => (pageSize.value = i),
  }

  return { ...toRefs(data), pageSize, pagination, handlePageChange, getData }
}

export default useGetData
